package io.github.wanggit.antrpc.gateway.starter;

import io.github.wanggit.antrpc.gateway.starter.zk.ZkConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

@Slf4j
public class ApplicationContextInitializedEventListener
        implements ApplicationListener<ApplicationContextInitializedEvent> {
    @Override
    public void onApplicationEvent(ApplicationContextInitializedEvent event) {
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String zkHosts = environment.getProperty("zookeeper.hosts", String.class);
        Integer zkConnectRetryBaseSleepMs =
                environment.getProperty("zookeeper.zkConnectRetryBaseSleepMs", Integer.class);
        Integer zkConnectMaxRetries =
                environment.getProperty("zookeeper.zkConnectMaxRetries", Integer.class);
        Integer zkConnectRetryMaxSleepMs =
                environment.getProperty("zookeeper.zkConnectRetryMaxSleepMs", Integer.class);
        Integer zkConnectionTimeoutMs =
                environment.getProperty("zookeeper.zkConnectionTimeoutMs", Integer.class);
        ZkConfig zkConfig = new ZkConfig();
        if (null != zkHosts) {
            zkConfig.setZkIps(zkHosts);
        }
        if (null != zkConnectRetryBaseSleepMs) {
            zkConfig.setZkConnectRetryBaseSleepMs(zkConnectRetryBaseSleepMs);
        }
        if (null != zkConnectMaxRetries) {
            zkConfig.setZkConnectMaxRetries(zkConnectMaxRetries);
        }
        if (null != zkConnectRetryMaxSleepMs) {
            zkConfig.setZkConnectRetryMaxSleepMs(zkConnectRetryMaxSleepMs);
        }
        if (null != zkConnectionTimeoutMs) {
            zkConfig.setZkConnectionTimeoutMs(zkConnectionTimeoutMs);
        }
        IGatewayContext gatewayContext = new GatewayContext();
        gatewayContext.init(zkConfig);
        applicationContext
                .getBeanFactory()
                .registerSingleton(IGatewayContext.class.getName(), gatewayContext);
    }
}
